/*
 * Copyright© 2003-2019 浙江汇信科技有限公司, All Rights Reserved.
 */
package com.icinfo.cloud.provider.punish.ucase.casemain.service.impl;

import com.icinfo.cloud.provider.common.constant.Constant;
import com.icinfo.cloud.provider.common.enums.RecordSaveTypeEnum;
import com.icinfo.cloud.provider.common.exception.BusinessException;
import com.icinfo.cloud.provider.common.utils.BaseUtil;
import com.icinfo.cloud.provider.punish.common.caseregister.service.IRegisterCommonService;
import com.icinfo.cloud.provider.punish.evideinv.service.EvidenceInventoryService;
import com.icinfo.cloud.provider.punish.ucase.casemain.dto.*;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.PartyTypeEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.mapper.CasePartiesLegalInfoMapper;
import com.icinfo.cloud.provider.punish.ucase.casemain.mapper.CasePartiesRecordMapper;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.CasePartiesLegalInfo;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.CasePartiesRecord;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.ICasePartiesLegalInfoService;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.ICasePartiesRecordService;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CasePartiesInfoVo;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CasePartiesLegalInfoVo;
import com.icinfo.framework.common.web.Result;
import com.icinfo.framework.core.service.support.MyBatisServiceSupport;
import com.icinfo.framework.mybatis.mapper.entity.Example;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 描述: 案件当事人法人详细信息-TRJ case_parties_legal_info 对应的Service接口实现类.<br>
 *
 * @author framework generator
 * @date 2022年02月15日
 */
@Service
@Slf4j
public class CasePartiesLegalInfoServiceImpl extends MyBatisServiceSupport implements ICasePartiesLegalInfoService {
    @Resource
    private CasePartiesLegalInfoMapper casePartiesLegalInfoMapper;
    @Resource
    private EvidenceInventoryService evidenceInventoryService;
    @Resource
    private CasePartiesRecordMapper casePartiesRecordMapper;
    @Resource
    private IRegisterCommonService commonService;
    @Resource
    private ICasePartiesRecordService casePartiesRecordService;

    /**
     * 【V1.0.0】描述：保存案件当事人-法人信息
     *
     * @param saveDto {@link CasePartiesLegalInfoDto}
     * @return int 保存成功记录数
     * @author xiangyuyu
     * @date 2022-02-18 16:02
     */
    @Override
    public int saveCasePartiesLegalInfo(CasePartiesLegalInfoDto saveDto) {
        //判断新增还是修改
        String operateType = saveDto.getOperateType();
        if(!RecordSaveTypeEnum.isLegalEnumCode(operateType)){
            throw new BusinessException("请指定有效的操作类型(1-新增/2-修改)");
        }
        //校验信息填充完整性
        String errorMsg = validateLegalInfo(saveDto);
        if(!ObjectUtils.isEmpty(errorMsg)){
            throw new BusinessException(errorMsg);
        }
        CasePartiesLegalInfo legalInfo = new CasePartiesLegalInfo();
        BeanUtils.copyProperties(saveDto, legalInfo);
        if(ObjectUtils.isEmpty(legalInfo.getId())){
            legalInfo.setId(BaseUtil.createUid());
        }
        int count;
        String caseId = saveDto.getCaseId();
        String partyId = saveDto.getId();
        if(RecordSaveTypeEnum.ADD.getCode().equals(operateType)){
            count = casePartiesLegalInfoMapper.insertSelective(legalInfo);
        } else {
            //校验caseId+partyId是否匹配，匹配后才允许修改
            CasePartiesRecordQueryDto queryDto = new CasePartiesRecordQueryDto();
            queryDto.setCaseId(caseId);
            queryDto.setPartyId(partyId);
            queryDto.setIsQueryInvalidData(saveDto.getIsQueryInvalidData());
            List<CasePartiesInfoVo> list = casePartiesRecordService.getCasePartiesInfoList(queryDto);
            if (!ObjectUtils.isEmpty(list) && list.size() > 0) {
                //允许修改
                count = casePartiesLegalInfoMapper.updateByPrimaryKeySelective(legalInfo);
            } else {
                throw new BusinessException("案件id和当事人id不匹配，无法进行更新");
            }
        }
        return count;
    }

    /**
     * 描述：校验法人信息
     *
     * @param dto {@link CasePartiesLegalInfoDto}
     * @return String 错误信息
     * @author xiangyuyu
     * @date 2022-06-20 11:46
     */
    private String validateLegalInfo(CasePartiesLegalInfoDto dto) {
        if (ObjectUtils.isEmpty(dto.getLegalName())) {
            return "法定代表人不能为空";
        }
        if (ObjectUtils.isEmpty(dto.getUniscid())) {
            return "统一社会信用代码不能为空";
        }
        /*if (ObjectUtils.isEmpty(dto.getPhone())) {
            return "单位的电话不能为空";
        }*/
        if (ObjectUtils.isEmpty(dto.getAddress())) {
            return "单位的地址不能为空";
        }
        if (ObjectUtils.isEmpty(dto.getEntName())) {
            return "单位名称不能为空";
        }
        if (ObjectUtils.isEmpty(dto.getEntType())) {
            return "单位类型不能为空";
        }
        return null;
    }

    /**
     * 【V1.0.0】描述：获取案件当事人-法人信息分页列表
     *
     * @param pageRequest {@link CasePartiesLegalInfoPageRequest}
     * @return {@link Result<  List  < CasePartiesLegalInfoVo >>} 案件当事人-法人信息分页列表
     * @author xiangyuyu
     * @date 2022-02-18 16:02
     */
    @Override
    public List<CasePartiesLegalInfoVo> getCasePartiesLegalInfoPageList(CasePartiesLegalInfoPageRequest pageRequest) {
        return null;
    }

    /**
     * 【V1.0.0】描述：获取案件当事人-法人信息列表
     *
     * @param queryDto {@link CasePartiesLegalInfoQueryDto}
     * @return {@link List<CasePartiesLegalInfoVo>} 案件当事人-法人信息列表
     * @author xiangyuyu
     * @date 2022-02-18 16:02
     */
    @Override
    public List<CasePartiesLegalInfoVo> getCasePartiesLegalInfoList(CasePartiesLegalInfoQueryDto queryDto) {
        return null;
    }

    /**
     * 【V1.0.0】描述：根据唯一标识查询案件当事人-法人信息
     *
     * @param id 唯一标识
     * @return {@link CasePartiesLegalInfoVo} 案件当事人-法人信息
     * @author xiangyuyu
     * @date 2022-02-18 16:02
     */
    @Override
    public CasePartiesLegalInfoVo getCasePartiesLegalInfo(String id) {
        log.info("getCasePartiesLegalInfo start(id:+" + id + ")...");
        CasePartiesLegalInfo casePartiesLegalInfo = casePartiesLegalInfoMapper.selectByPrimaryKey(id);
        if (ObjectUtils.isEmpty(casePartiesLegalInfo)) {
            throw new BusinessException("未找到个人信息");
        }
        CasePartiesLegalInfoVo vo = new CasePartiesLegalInfoVo();
        BeanUtils.copyProperties(casePartiesLegalInfo, vo);
        log.info("getCasePartiesLegalInfo end-vo:" + vo);
        return vo;
    }

    /**
     * 【V1.0.0】描述：删除案件当事人-法人信息
     *
     * @param id 主键id
     * @return {@link Result<String>} 删除结果
     * @author xiangyuyu
     * @date 2022-02-18 16:02
     */
    @Override
    public Result<String> removeCasePartiesLegalInfo(String id) {
        return null;
    }


    /***
     * @Author: zhengqiang
     * @Date: 2022/5/12
     * @Description: 更新法定代表人证件信息
     * @param: casePartiesLegalInfoSaveDto
     * @return: boolean
     **/
    @Override
    public Result<String> updateCasePartiesLegalInfo(CasePartiesLegalInfoUpdateDto casePartiesLegalInfoUpdateDto) {
        //判断法定代表人记录是否存在
        CasePartiesLegalInfo legalInfo = casePartiesLegalInfoMapper.selectByPrimaryKey(casePartiesLegalInfoUpdateDto.getId());
        if (legalInfo == null) {
            return Result.error("法定代表人记录不存在");
        }

        //验证姓名和证件号码是否匹配
        if(StringUtils.isNotEmpty(casePartiesLegalInfoUpdateDto.getLegalCertNo()) && "SFZ".equals(casePartiesLegalInfoUpdateDto.getLegalCertType())){
            boolean flag = commonService.checkRealNameDifferent(casePartiesLegalInfoUpdateDto.getLegalCertNo(), casePartiesLegalInfoUpdateDto.getLegalName());
            if(flag){
                return Result.error("证件号码和姓名不匹配");
            }
        }

        CasePartiesLegalInfo updateLegalInfo = new CasePartiesLegalInfo();
        BeanUtils.copyProperties(casePartiesLegalInfoUpdateDto, updateLegalInfo);

        int i = casePartiesLegalInfoMapper.updateByPrimaryKeySelective(updateLegalInfo);
        if (i > 0) {
            //调用更新案件-当事人信息接口
            //要求接口调用失败不影响业务继续执行
            try {
                Example example=new Example(CasePartiesRecord.class);
                example.createCriteria().andEqualTo("partyId", casePartiesLegalInfoUpdateDto.getId()).andEqualTo("status", Constant.STRING_1);
                List<CasePartiesRecord> casePartiesRecords=casePartiesRecordMapper.selectByExample(example);
                CasePartiesRecord casePartiesRecord = casePartiesRecords.get(0);
                evidenceInventoryService.updateCpInfo(casePartiesRecord.getCaseId());
            } catch (Exception e) {
                e.printStackTrace();
            }
            return Result.success("更新成功");
        }
        return Result.error("更新失败");
    }

    /**
     * 描述：获取缺失法人证件信息的法定代表人信息
     *
     * @param caseId 案件id
     * @return {@link List<CasePartiesLegalInfoVo>}
     * @author xiangyuyu
     * @date 2022-05-23 10:02
     */
    @Override
    public List<CasePartiesLegalInfoVo> getLegalInfoWhoLoseLegalCertInfo(String caseId) {
        return casePartiesLegalInfoMapper.selectLegalInfoWhoLoseLegalCertInfo(caseId);
    }

    /**
     * 根据caseId获取有效的单位数据
     * @param caseId
     * @return
     */
    @Override
    public CasePartiesLegalInfo getInfoByCaseId(String caseId){
        return casePartiesLegalInfoMapper.getInfoByCaseId(caseId);
    }

    @Override
    public List<CasePartiesLegalInfoDto> getCasePartiesLegalInfoDtoList(String caseId) {
        List<CasePartiesLegalInfoDto> legalInfoDtoList=new ArrayList<>();
        Example example=new  Example(CasePartiesLegalInfo.class);
        example.createCriteria().andEqualTo("caseId",caseId);
        List<CasePartiesLegalInfo> casePartiesPersonInfoList = casePartiesLegalInfoMapper.selectByExample(example);
        for (CasePartiesLegalInfo casePartiesLegalInfo: casePartiesPersonInfoList){
            CasePartiesLegalInfoDto legalInfoDto=new CasePartiesLegalInfoDto();
            BeanUtils.copyProperties(casePartiesLegalInfo,legalInfoDto);
            legalInfoDto.setPartyId(casePartiesLegalInfo.getId());
            legalInfoDtoList.add(legalInfoDto);
        }
        return legalInfoDtoList;
    }



    /**
     * 【V1.0.0】描述：保存案件调整当事人-法人信息
     *
     * @param saveDto {@link CasePartiesLegalInfoDto}
     * @return int 保存成功记录数
     * @author xiangyuyu
     * @date 2022-02-18 16:02
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String saveCasePartiesLegalInfoWithAdjust(CasePartyRecordAdjustLegalSaveDto saveDto) {
        //判断新增还是修改
        String operateType = saveDto.getOperateType();
        if(!RecordSaveTypeEnum.isLegalEnumCode(operateType)){
            throw new BusinessException("请指定有效的操作类型(1-新增/2-修改)");
        }
        CasePartiesLegalInfo legalInfo = new CasePartiesLegalInfo();
        BeanUtils.copyProperties(saveDto, legalInfo);
        if(ObjectUtils.isEmpty(legalInfo.getId())){
            legalInfo.setId(BaseUtil.createUid());
        }
        int count;
        String caseId = saveDto.getCaseId();
        String partyId = saveDto.getId();
        saveDto.setPartyIdentityCode(saveDto.getUniscid());
        saveDto.setPartyType(PartyTypeEnum.LEGAL.getCode());
        saveDto.setPartyIdentityType(null);
        CasePartiesRecord casePartiesRecord = new CasePartiesRecord();
        BeanUtils.copyProperties(saveDto, casePartiesRecord);
        casePartiesRecord.setAddressAreas(saveDto.getAddressAreas());
        casePartiesRecord.setCaseId(caseId);
        casePartiesRecord.setAddressAreas(saveDto.getAddressAreas());
        casePartiesRecord.setAddressDetail(saveDto.getAddressDetail());
        casePartiesRecord.setPartyIdentityCode(saveDto.getUniscid());
        casePartiesRecord.setPartyIdentityType(null);
        casePartiesRecord.setPartyName(saveDto.getEntName());
        casePartiesRecord.setPartyType(PartyTypeEnum.LEGAL.getCode());
        casePartiesRecord.setPartyId(partyId);
        casePartiesRecord.setId(BaseUtil.createUid());
        if(RecordSaveTypeEnum.ADD.getCode().equals(operateType)){
            count = casePartiesLegalInfoMapper.insertSelective(legalInfo);
        } else {
            //校验caseId+partyId是否匹配，匹配后才允许修改
            CasePartiesRecordQueryDto queryDto = new CasePartiesRecordQueryDto();
            queryDto.setCaseId(caseId);
            queryDto.setPartyId(partyId);
            queryDto.setIsQueryInvalidData(saveDto.getIsQueryInvalidData());
            List<CasePartiesInfoVo> list = casePartiesRecordService.getCasePartiesInfoList(queryDto);
            if (!ObjectUtils.isEmpty(list) && list.size() > 0) {
                //允许修改
                count = casePartiesLegalInfoMapper.updateByPrimaryKeySelective(legalInfo);
                //将修改前的无效掉
                casePartiesRecordService.delCasePartiesRecordByPartyId(partyId);
            } else {
                throw new BusinessException("案件id和当事人id不匹配，无法进行更新");
            }
        }
        //保存到当事人信息表
         casePartiesRecordMapper.insertSelective(casePartiesRecord);
        return partyId;
    }

 }
